package com.smile.presenter;

import com.google.gson.Gson;
import com.smile.interf.RegisterInterface;
import com.smile.interf.ViewInterface;
import com.smile.model.ReceiveString;
import com.smile.server.ChatManager;

public class RegisterPresenter implements ViewInterface {

	private RegisterInterface registerInterface;
	private boolean isConn = false;
	private Gson gson = new Gson();

	public RegisterPresenter(RegisterInterface registerInterface) {
		this.registerInterface = registerInterface;
		ChatManager.getCM().setViewInterface(this);
	}

	public boolean getIsConn() {
		return isConn;
	}

	public void register(String name, String password, String rePassword) {
		if (isConn) {
			if (name.equals("")) {
				registerInterface.setErrorMessage(1, "请输入昵称");
				registerInterface.setRegisterButton(true);
			} else if (password.equals("")) {
				registerInterface.setErrorMessage(2, "请输入密码");
				registerInterface.setRegisterButton(true);
			} else if (!rePassword.equals(password)) {
				registerInterface.setErrorMessage(3, "两次密码不同");
				registerInterface.setRegisterButton(true);
			} else {
				registerInterface.setRegisterButton(false);
				ChatManager.getCM().register(name, password);
			}
		}

	}

	public void conn() {
		isConn = ChatManager.getCM().isConn;
		if (!isConn) {
			ChatManager.getCM().connect();
		}
	}

	@Override
	public void setMessage(String json) {
		ReceiveString receiveString = gson.fromJson(json, ReceiveString.class);

		switch (receiveString.getCode()) {
		case 1:
			registerInterface.setRegisterMessage(true, receiveString.getJson());
			break;
		case 1062:
			registerInterface.setErrorMessage(1, "该昵称已存在");
			registerInterface.setRegisterButton(true);
			break;

		default:
			break;
		}
	}

	@Override
	public void setConnMessage(boolean is, String message) {
		if (!is) {
			System.out.println(message);
		}
		isConn = is;
		registerInterface.setConn(isConn);
	}

}
